home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / linux / docs / dd-tutorial.doc.z / dd-tutorial.doc
Encoding:
Text File  |  1993-04-12  |  42.2 KB  |  1,136 lines

  1. ************************************************************
  2. *                                                          *
  3. *  Tutorial To Linux Driver Writing -- Character Devices   *
  4. *                                                          *
  5. *                            or,                           *
  6. *                                                          *
  7. *       Now That I'm Wacky, Let Me Do Something (I)        *
  8. *                                                          *
  9. *                 Last Revision: Apr 11, 1993              *
  10. *                                                          *
  11. ************************************************************
  12.  
  13. This document (C) 1993 Robert Baruch.  This document may be freely 
  14. copied as long as the entire title, copyright, this notice, and all of
  15. the introduction are included along with it.  Suggestions, criticisms,
  16. and comments to baruch@nynexst.com.  This document, nor the work
  17. performed by Robert Baruch using Linux, nor the results of said work
  18. are connected in any way to any of the Nynex companies.  This product
  19. 0% organic as defined by California Statute 4Z//7&A.  No artificial
  20. coloring or flavoring.
  21.  
  22. ========================
  23.      Introduction
  24. ========================
  25.  
  26. There is a companion guide to this Tutorial, the Guide to Linux Driver
  27. Writing -- Character Devices This Guide should serve as a reference to 
  28. both beginning and advanced driver writers, and should be used in
  29. conjunction with this Tutorial.
  30.  
  31. -=-=-=-=-=-=-
  32.  
  33. Some words of thanks:
  34.  
  35. Many thanks to:
  36.  
  37.  Donald J. Becker (becker@metropolis.super.org)
  38.  Don "May the Source be With You!" Holzworth (donh@gcx1.ssd.csd.harris.com)
  39.  Michael Johnson (johnsonm@stolaf.edu)
  40.  Karl Heinz Kremer (khk@raster.kodak.com)
  41.  Pat Mackinlay (mackinla@cs.curtin.edu.au)
  42.  ...others too numerous to mention...
  43.  All the driver writers!
  44.  
  45. ...and of course, Linus "That's LIN-uhks" Torvalds and all the guys who helped
  46.  develop Linux into a BLOODY KICKIN' O/S!
  47.  
  48. -=-=-=-=-=-=-
  49.  
  50. ...and now a word of warning:
  51.  
  52. Messing about with drivers is messing with the kernel.  Drivers are run
  53. at the kernel level, and as such are not subject to scheduling.  Further,
  54. drivers have access to various kernel structures.  Before you actually
  55. write a driver, be *damned* sure of what you are doing, lest you end
  56. up having to re-format your harddrive and re-install Linux!
  57.  
  58. The information in this Tutorial is as up-to-date as I could make it.  It also
  59. has no stamp of approval whatsoever by any of the designers of the kernel.
  60. I am not responsible for damage caused to anything as a result of using this
  61. Guide.
  62.  
  63. ========================
  64.   End of Introduction
  65. ========================
  66.  
  67.  
  68. CHAPTRE THE FIRSTE : How did *they* get the device driver in the kernel?
  69. ------------------
  70.  
  71. You have to realize that device drivers really are part of the kernel.  The
  72. kernel can hook in to the functions in your device driver if you tell it
  73. the addresses of some standard functions.  These standard functions are
  74. detailed in the Guide.
  75.  
  76. As a part of the kernel, the code of the device driver must be compiled in
  77. *with* the kernel.  That is, you must alter some Makefiles to compile your
  78. driver and to get it archived into the chr_drv.a library, or you can
  79. archive it yourself and link it in to the kernel at a later compile stage.
  80.  
  81. The first step, before you even write a single line of driver code, is to
  82. make sure you know how to recompile the kernel.  Then go ahead and actually
  83. do it, to be sure you (and your system) are sane.  Of course, you need
  84. the sources to the kernel.  If you have the SLS distribution of Linux, you
  85. already have the sources in /linux.  If you don't have the sources, you
  86. can get it at one of these fine ftp sites near you:
  87.  
  88.   tsx-11.mit.edu:/pub/linux
  89.   sunsite.unc.edu:/pub/Linux
  90.  
  91. Briefly, here's how to compile the kernel (at least this is how it's done
  92. in the SLS release):
  93.  
  94. Go to /linux (or wherever the source for Linux is)
  95. You will see a directory which looks a lot like this:
  96.  
  97. -rw-r--r--  1 baruch      17982 Nov 10 07:54 COPYING
  98. -rw-r--r--  1 baruch       1444 Jan 13 15:24 Configure
  99. -rw-r--r--  1 baruch       6934 Feb 22 13:31 Makefile
  100. -rw-r--r--  1 baruch       4078 Dec 12 06:45 README
  101. drwxrwxr-x  2 baruch        512 Feb 22 13:34 boot
  102. -rw-r--r--  1 baruch       1724 Feb  9 15:07 config.in
  103. drwxrwxr-x  8 baruch        512 Feb 22 13:34 fs
  104. drwxrwxr-x  4 baruch        512 Dec  1 19:40 include
  105. drwxrwxr-x  2 baruch        512 Feb 22 13:34 init
  106. drwxrwxr-x  5 baruch        512 Feb  9 15:11 kernel
  107. drwxrwxr-x  2 baruch        512 Feb  9 15:11 lib
  108. -rwxr-xr-x  1 baruch        166 Nov 10 07:54 makever.sh
  109. drwxrwxr-x  2 baruch        512 Feb 22 13:34 mm
  110. drwxrwxr-x  3 baruch        512 Feb  9 15:11 net
  111. drwxrwxr-x  2 baruch        512 Feb 22 13:34 tools
  112. drwxrwxr-x  2 baruch        512 Feb 22 13:34 zBoot
  113.  
  114. The README file should contain instructions, but here's how anyway:
  115.  
  116. Log in as root.
  117.  
  118. make clean   (Do this only once.  Otherwise you'll have to sit around
  119.               for 45 minutes or so while the whole thing recompiles)
  120. make config  (Answer the questions -- usually needed only the first time)
  121. make dep     (Makes dependencies)
  122. make         (makes the kernel)
  123.  
  124. You should end up with an Image file.  This is the kernel.  Put it where
  125. you like (LILO users should take it from there).  To make a bootable disk,
  126. just pop a DOS formatted disk in drive A, and do:
  127.  
  128. make disk
  129.  
  130. ------------------------------------------------------------------------
  131.  
  132. CHAPTER TWO: The simplest driver you've ever seen.
  133. ------------
  134.  
  135. Now, the directory you're interested in is <src>/kernel/chr_drv.  This is
  136. where all the character device drivers are kept.  Go to that directory.
  137. Open up a new file, and call it testdata.c.  Here is what you should
  138. put in it:
  139.  
  140. ========================================
  141.       File Listing 1: testdata.c
  142. ========================================
  143.  
  144. #include <linux/kernel.h>
  145. #include <linux/sched.h>
  146. #include <linux/tty.h>
  147. #include <linux/signal.h>
  148. #include <linux/errno.h>
  149.  
  150. #include <asm/io.h>
  151. #include <asm/segment.h>
  152. #include <asm/system.h>
  153. #include <asm/irq.h>
  154.  
  155. unsigned long test_init(unsigned long kmem_start)
  156. {
  157.   printk("Test Data Generator installed.\n");
  158.   return kmem_start;
  159. }
  160.  
  161. ========================================
  162.  
  163. The include files are all there for convenience.  You may need them later.
  164. All this driver does is upon initialization, display a message.
  165.  
  166. Now, to get this driver into the kernel, you need to do several things.
  167. The first two things do in the chr_drv directory:
  168.  
  169. I.  Get the kernel to call your init function on bootup.  To do this,
  170.     edit the mem.c file, and go to the very end to the function
  171.     chr_drv_init.  It looks something like this:
  172.  
  173.   long chr_dev_init(long mem_start, long mem_end)
  174.   {
  175.         if (register_chrdev(1,"mem",&memory_fops))
  176.                 printk("unable to get major 1 for memory devs\n");
  177.         mem_start = tty_init(mem_start);
  178.         mem_start = lp_init(mem_start);
  179.         mem_start = mouse_init(mem_start);
  180.         mem_start = soundcard_init(mem_start);
  181.         return mem_start;
  182.   }
  183.  
  184.     You need to add your test_init function to the code.  Put it right
  185.     before the return:
  186.  
  187.   mem_start = test_init(mem_start);
  188.  
  189.     Save the file.
  190.  
  191. II.  Edit the Makefile to compile testdata.c.  Edit the Makefile, and add
  192.      testdata.o to the OBJS list.  This will cause the make utility to
  193.      compile testdata.c into an object file, and then add it to the
  194.      chr_drv.a library archive.
  195.  
  196.      Save the file.
  197.  
  198. The next step is to re-compile the kernel.  Go to the <src> directory,
  199. and do a make from the top as described in the first chapter.  There is
  200. no point in doing a "make clean" or "make config".  If all goes well, the 
  201. make should proceed down to chr_drv, and compile your testdata.c file.  
  202. If there are warnings or errors, do a ctrl-C to break out of the make, 
  203. and fix the problem.
  204.  
  205. Once you are left with an Image file, put the Image file where LILO
  206. wants it, or use "make disk" to make a bootable disk.  It's a good
  207. idea to save your old Image file (or save the disk it was on).
  208.  
  209. Now reboot.  When Linux comes up again, you should see your message
  210. printed on bootup after all the character devices' messages, before
  211. any of the block device messages.  If the message came up, have a soda.
  212. Jump up and down a little.  (Well, first jump, _then_ have the soda).
  213.  
  214. If it didn't work, go back and find out what you did wrong.  Are you
  215. sure you recompiled the kernel?  Did it recompile with testdata.c?  Did
  216. you reboot using the new kernel?  Are you sure? Are you root? Maybe
  217. your kernel is bad or old.  I have used 0.99pl6, with the new libc.so.4.3.2
  218. shared library successfully, and I am currently using 0.99pl8 with
  219. libc.so.4.3.3.
  220.  
  221.  
  222. ------------------------------------------------------------------------
  223.  
  224. CHAPTER THREE: A device driver that actually does something useful.
  225. -------------
  226.  
  227. This example is taken from the _Writing UNIX Device Drivers_ book by
  228. George Pajari, published by Addison Wesley.  It can usually be found
  229. in a Barnes and Noble bookstore, or any large bookstore which has
  230. a nice section on UNIX.  The ISBN is 0-201-52374-4, and it was published
  231. in 1992.  This book is highly recommended for the device driver writer.
  232.  
  233. This device driver will actually be read from.  You can open and close
  234. it (which really won't do much), but the biggest thing it will do is
  235. allow you to read from it.  This driver won't access any external hardware,
  236. and so it is called a "pseudo device driver".  That is, it really doesn't
  237. drive any device.
  238.  
  239. Have your Guide handy?  OK, now alter your testdata.c file so that it
  240. looks like this:
  241.  
  242. ========================================
  243.       File Listing 2: testdata.c
  244. ========================================
  245.  
  246. #include <linux/kernel.h>
  247. #include <linux/sched.h>
  248. #include <linux/tty.h>
  249. #include <linux/signal.h>
  250. #include <linux/errno.h>
  251.  
  252. #include <asm/io.h>
  253. #include <asm/segment.h>
  254. #include <asm/system.h>
  255. #include <asm/irq.h>
  256.  
  257. static char test_data[]="Linux is really funky!\n";
  258.  
  259. static int test_read(struct inode * inode, struct file * file, 
  260.                      char * buffer, int count)
  261. {
  262.   int offset;
  263.  
  264.   printk("Test Data Generator, reading %d bytes\n",count);  
  265.   if (count<=0) return -EINVAL;
  266.   for (offset=0; offset<count; offset++)
  267.     put_fs_byte(test_data[offset % (sizeof(test_data)-1)], buffer+offset);
  268.   return offset;
  269. }
  270.  
  271. static int test_open(struct inode *inode, struct file *file)
  272. {
  273.   printk("Test Data Generator opened.\n");
  274.   return 0;
  275. }
  276.  
  277. static void test_release(struct inode *inode, struct file *file)
  278. {
  279.   printk("Test Data Generator released.\n");
  280. }
  281.  
  282. struct file_operations test_fops = {
  283.     NULL,        /* test_seek */
  284.     test_read,    /* test_read */
  285.     NULL,        /* test_write */
  286.     NULL,         /* test_readdir */
  287.     NULL,         /* test_select */
  288.     NULL,         /* test_ioctl */
  289.     NULL,        /* test_mmap */
  290.     test_open,    /* test_open */
  291.     test_release    /* test_release */
  292. };
  293.  
  294. unsigned long test_init(unsigned long kmem_start)
  295. {
  296.   printk("Test Data Generator installed.\n");
  297.   if (register_chrdev(21,"test",&test_fops));
  298.     printk("Test Data Generator error: Cannot register to major device 21!\n");
  299.   return kmem_start;
  300. }
  301.  
  302. ========================================
  303.  
  304. OK, let's go over this.  Look first at the test_init function.  Notice
  305. the new function -- register_chrdev.  This registers the character device
  306. with the kernel as using major device number 21.  All devices (except for
  307. the really simple one in the last chapter) use major device numbers to
  308. be accessed.  The kernel has an internal table of devices and their
  309. associated device functions which is indexed by major device number.
  310.  
  311. The device numbers go from 0 to MAX_CHRDEV-1.  MAX_CHRDEV is defined in
  312. linux/fs.h, and is currently set at 32.  In general, you want to stay away
  313. from devices 0-15 because those are reserved for the "usual" devices.
  314. Currently, these usual devices (according to the FAQ) are as follows:
  315.  
  316. ---Excerpt from FAQ begins---
  317.  
  318. QUESTION: What are the device minor/major numbers?
  319.  
  320.                         The Linux Device List
  321.     maintained by rick@ee.uwm.edu (Rick Miller, Linux Device Registrar)
  322.                           February 17, 1993
  323.  
  324. Many thanks to richard@stat.tamu.edu, Jim Winstead Jr., and many others.
  325.  
  326. Majors:
  327.  0.  Unnamed .  (unknown) ....  for proc-fs, NFS clients, etc.
  328.  1.  Memory ..  (character) ..  ram, mem, kmem, null, port, zero
  329.  2.  Floppy ..  (block) ......  fd[0-1]<[dhDH]{360,720,1200,1440}>
  330.  3.  Hard Disk  (block) ......  hd[a-b]<[0-8]>
  331.  4.  Tty .....  (character) ..  {p,t}ty<{S,[p-s][0-f]}><#>
  332.  5.  tty .....  (character) ..  tty, cua[0-63]
  333.  6.  Lp ......  (character) ..  lp[0-2] or par[0-2]
  334.  7.  Tape ....  (block) ......  t[0-?] (reserved for Non-SCSI tape drives)
  335.  8.  Scsi Disk  (block) ......  sd[a-h]<[0-8]>
  336.  9.  Scsi Tape  (block) ......  <n>rmt[0-1]
  337. 10.  Mouse ...  (character) ..  bm, psaux (mouse)
  338. 11.  CD-ROM ..  (block) ......  scd[0-1]
  339. 12.  QIC-tape?  (character) ..  rmt{8,16}, tape<{-d,-reset}>
  340. 13.  XT-disk .  (block) ......  xd[a-b]<[0-8]>
  341. 14.  Audio ...  (character) ..  audio, dsp, midi, mixer, sequencer
  342.  
  343. ---Excerpt from FAQ ends---
  344.  
  345. The FAQ goes on to break down the major devices by minor numbers.  Each major
  346. device can be broken down into at most 256 minor devices (0-255).  The
  347. device driver can determine which minor it is supposed to operate on.  More
  348. on that later.
  349.  
  350. In any case, I've chosen major 21 for experimentation purposes.  By the way,
  351. the name of the driver (here it's "test") is not important.  The kernel does
  352. not do anything with it.  [It would be nice if it would.  Then you could
  353. interrogate the kernel and find out what drivers are installed!]
  354.  
  355. register_chrdrv also takes in a pointer to a file_operations structure.  This
  356. structure tells the kernel which function to call for which kernel operation.
  357. The details of this structure is given in the Guide.  For now, what is
  358. important is that we are telling the kernel to call test_read for read
  359. operations, test_open for open operations, and test_close for release
  360. operations.
  361.  
  362. If a driver has already taken major 21, register_chrdrv will return -EBUSY.
  363. Here, all we do is print a message saying that 21 is already taken.
  364.  
  365. Now, the test_open and test_release functions just print out things to
  366. the console.  They are really there for debugging purposes, so that you
  367. can see when things happen.
  368.  
  369. The meat of the driver is the test_read function.  The first thing it does
  370. is print out how many bytes were requested.  Then it puts that many bytes
  371. into user space.  Remember that the driver is executing at the kernel level,
  372. and the user space will be differnet from kernel space.  We have to do
  373. some kind of translation to put the data which is in kernel space into
  374. the buffer which is in user space.  We use here the put_fs_byte function.
  375.  
  376. The loop puts the string into the buffer, going back to the beginning of
  377. the string if necessary.  Once the loop is finished, we just return the
  378. actual number of bytes read.  The actual number may be different from the
  379. requested number.  For example, you may be reading from the driver some kind
  380. of message which has a fixed size.  You may want to code the driver so that
  381. if you attempt to read more than the message size, you will get only the
  382. message size, and no more.  Here, we just give the process however many
  383. bytes it wants.
  384.  
  385. Now, let's get this driver into the kernel.  But first what we'll do is
  386. create a special file which can be opened, read, and closed.  Operations on
  387. this special file will activate your driver code.
  388.  
  389. The special files are normally stored in the /dev directory. Do this:
  390.  
  391.   mknod /dev/testdata c 21 0
  392.   chmod 0666 /dev/testdata
  393.  
  394. This makes a special character (c) file called testdata, and gives it major
  395. 21, minor 0.  The chmod makes sure that everyone can read and write the
  396. device.
  397.  
  398. Now recompile the kernel, and reboot.  Once again, make sure you fix any
  399. warnings or errors in your testdata.c compilation.
  400.  
  401. Now, go to the /tmp directory (or whereever you want), and write this
  402. program:
  403.  
  404. ========================================
  405.       File Listing 3: data.c
  406. ========================================
  407.  
  408. #include <stdio.h>
  409. #include <sys/types.h>
  410. #include <unistd.h>
  411. #include <fcntl.h>
  412.  
  413. void main(void)
  414. {
  415.   int fd;
  416.   char buff[128];
  417.   
  418.   fd = open("/dev/testdata",O_RDWR);
  419.   printf("/dev/testdata opened, fd=%d\n",fd);
  420.   if (fd<=0) exit(0);
  421.   printf("sizeof(buff)=%d\n",sizeof(buff));
  422.   printf("Read returns %d\n",read(fd,buff,sizeof(buff)));
  423.   buff[127]=0;
  424.   printf("buff=\n'%s'\n",buff);
  425.   close(fd);
  426. }
  427.  
  428. ========================================
  429.  
  430. Compile it using gcc.  Run it.  If it said "Linux is really funky!" lots
  431. of times, pat yourself on the back (or whereever you want) for a job
  432. well done.  If it didn't, check the output, and see where you went wrong.
  433. It could just be that you have a bad or old kernel.
  434.  
  435. The last line may be partial, since you're only printing out 127 characters.
  436.  
  437. ++++++++++++++++++++++
  438.     EXPERIMENT 1
  439. ++++++++++++++++++++++
  440.  
  441. Use mknod to make another special file, this one with minor 1.  Call it
  442. something like /dev/testdata2.  Change the device driver so that in the 
  443. read call, it finds out which minor is being read from.  Use this:
  444.  
  445.   int minor = MINOR(inode->i_rdev);
  446.  
  447. Print out the minor number, and depending on which minor it is, read 
  448. from a different message string.  Test your driver with code similar to
  449. data.c.
  450.  
  451. ++++++++++++++++++++++
  452.  
  453. ------------------------------------------------------------------------
  454.  
  455. CHAPTER FOUR: You've learned to read, now you're gonna learn to write.
  456. ------------
  457.  
  458. Now that you're reading strings, you may want to write strings and read them
  459. back.  We'll go through two versions of this -- one that uses static memory,
  460. and one that dynamically allocates the memory.
  461.  
  462. Keeping your current driver, all you need to do is add a write function to
  463. it, not forgetting to put that write function into the file_operations
  464. structure of the driver.
  465.  
  466. Add this section of code to your driver above the file_operations structure
  467. declaration:
  468.  
  469. ========================================
  470.   File Listing 4 (partial): testdata.c
  471. ========================================
  472.  
  473. static char test_data[128]="\0";
  474. static int test_data_size=0;
  475.  
  476. static int test_write(struct inode * inode, struct file * file,
  477.   char * buffer, int count)
  478. {
  479.   printk("Write %d bytes\n",count);
  480.   if (count>127) return -ENOMEM;
  481.   if ((!test_data_size) || (count<=0)) return -EINVAL;
  482.   memcpy_fromfs((void *)test_data, (void *)buffer, (unsigned long)count);
  483.   test_data[127]=0;  /* NUL-terminate the string if necessary */
  484.   test_data_size = count;
  485.   return count;
  486. }
  487.  
  488. ========================================
  489.  
  490. Also, alter the test_read function so that instead of using sizeof(test_data)
  491. as the size of the test_data string, it uses test_data_size.
  492.  
  493. In the test_write function, I have decided to prevent the acceptance of 
  494. strings which are too big to fit (with a NUL-terminator) into the test_data
  495. area, rather than just writing only what fits.  In this case, if the offered
  496. string is too long, I return ENOMEM.  The write function in the user's
  497. process will return <0, and errno will be set to ENOMEM.
  498.  
  499. Also note that I have used the memcpy_fromfs function, which is real
  500. convenient -- much more convenient than looping a put_fs_byte.
  501.  
  502. Compile this driver, and test it by modifying data.c to write some data,
  503. then read it back.
  504.  
  505. ++++++++++++++++++++++
  506.     EXPERIMENT 2
  507. ++++++++++++++++++++++
  508.  
  509. Re-write the driver so that it can have two different strings for the two
  510. minor devices as in experiment 1.
  511.  
  512. ++++++++++++++++++++++
  513.  
  514. Now that we can write data to the driver, it would be nice if we could 
  515. dynamically allocate memory to store a string in.  We will use kmalloc to
  516. do this. (Why is discussed later)
  517.  
  518. One thing which must be realized with kmalloc -- it can only allocate a
  519. maximum of one Linux page (4096 bytes).  If you want more, you will have
  520. to create a linked list.
  521.  
  522. Change your driver so that instead of listing 4, you have this:
  523.  
  524. ========================================
  525.   File Listing 5 (partial): testdata.c
  526. ========================================
  527.  
  528. static char *test_data=NULL;
  529. static int test_data_size=0;
  530.  
  531. static int test_write(struct inode * inode, struct file * file,
  532.   char * buffer, int count)
  533. {
  534.   printk("Write %d bytes\n",count);
  535.   if (count>4095) return -ENOMEM;
  536.   if (test_data!=NULL) kfree_s((void *)test_data, test_data_size);
  537.   test_data_size = 0;
  538.   test_data = (char *)kmalloc((unsigned int)count, GFP_KERNEL);
  539.   if (test_data==NULL) return -ENOMEM;
  540.   memcpy_fromfs((void *)test_data, (void *)buffer, (unsigned long)count);
  541.   test_data[count]=0;  /* NUL-terminate the string if necessary */
  542.   test_data_size = count;
  543.   return count;
  544. }
  545.  
  546. ========================================
  547.  
  548. Here, instead of statically allocating memory for the string, we dynamically
  549. allocate it using kmalloc.  Note first, that if we had already allocated
  550. a string, we free it first by using kfree_s.  This is faster than using
  551. kfree, because kfree would have to search for the size of the object allocated.
  552. Here we know what the size was, so we can use kfree_s.  kmalloc vs. malloc
  553. is discussed below.
  554.  
  555. Next, note that we use the GFP_KERNEL priority in the kmalloc.  This causes
  556. the process to go to sleep if there is no memory available, and the process
  557. will wake up again when there is memory to spare.  In general, the process
  558. will sleep until a page of memory is swapped out to disk.
  559.  
  560. In the event of catastrophic memory non-availability, kmalloc will return
  561. NULL, and we should handle that case.  Unfortunately here, we have already
  562. freed the previous string -- although that could be changed easily by
  563. kmallocing, then kfreeing.
  564.  
  565. The rest of the code reads as in listing 4.
  566.  
  567. When we get into the section on interrupt handling, we will discuss the
  568. use of GFP_ATOMIC as a kmalloc priority.
  569.  
  570. A brief excursion into kmalloc vs. malloc:
  571.  
  572. The malloc() call allocates memory in user space, which is fine if that's what
  573. you want.  Here, we want to have the driver store information so that *any*
  574. process can use it, and so we have to allocate memory in the kernel.  That
  575. means, kmalloc().  Further, there is a maximum of 4096 bytes which can be
  576. allocated in any one call of kmalloc.  This means that you cannot be guaranteed
  577. to get contiguous space of over 4096 bytes.  You will have to use a linked
  578. list of kmalloced buffers.
  579.  
  580. Alternatively, you can fool with the init section of the driver, and reserve
  581. contiguous space for yourself on init (but then it may as well be statically
  582. allocated).
  583.  
  584. ------------------------------------------------------------------------
  585.  
  586. CHAPTER FIVE: For my next trick, I...fall....a...sleep (SNNXXXX!!)
  587. ------------
  588.  
  589. The thing which really saves multitasking operating systems is that
  590. many process sleep when waiting for events to occur.  If this were not
  591. true, processes would always be burning cycles, and there would really
  592. be no big difference between running your processes at the same time,
  593. or one after the other.
  594.  
  595. But when a process sleeps, other processes get to use the CPU.  In general,
  596. processes sleep when an event they are waiting for has not yet happened.  The
  597. exception to this is processes which are designed to do work when nothing
  598. is happening.  For example, you might have a process sitting around using
  599. cycles to calculate pi out to a zillion digits.  That kind of background
  600. process should have its priority set real low so that it isn't executed
  601. often when other (presumably more important) processes have work to do.
  602.  
  603. Since processes sleep when waiting for events, and said events are usually
  604. handled by drivers, drivers must cause the processes which called them to
  605. sleep if not ready.  This is the idea behind the select() call, which will
  606. be dealt with in a later chapter.
  607.  
  608. To illustrate sleeping and waking processes, we will alter our driver from
  609. listing 2 by adding a new write function and changing the read function
  610. around as follows:
  611.  
  612. ========================================
  613.   File Listing 6 (partial): testdata.c
  614. ========================================
  615.  
  616. static char test_data[]="Linux is really funky!\n";
  617. static int wakeups = 0;
  618. static struct wait_queue *wait_queue = NULL;
  619.  
  620. static int test_write(struct inode * inode, struct file * file,
  621.   char * buffer, int count)
  622. {
  623.   int i;
  624.  
  625.   printk("Write %d bytes\n",count);
  626.   wake_up_interruptible(&wait_queue);
  627.   printk("Woke %d processes.\n",wakeups);
  628.   wakeups = 0;
  629.   return count;
  630. }
  631.  
  632. static int test_read(struct inode * inode, struct file * file, 
  633.                      char * buffer, int count)
  634. {
  635.   int offset;
  636.  
  637.   printk("Test Data Generator, reading %d bytes\n",count); 
  638.  
  639.   printk("Process going to sleep\n");
  640.   wakeups++;
  641.   interruptible_sleep_on(&wait_queue);
  642.   printk("Process has woken up!\n");
  643.  
  644.   for (offset=0; offset<count; offset++)
  645.     put_fs_byte(test_data[offset % (sizeof(test_data)-1)], buffer+offset);
  646.   return offset;
  647. }
  648.  
  649. ========================================
  650.  
  651. Don't forget to put the test_write function in the file_operations struct!
  652. But don't compile this driver just yet!  Read on...
  653.  
  654. The operation of this driver is as follows:  On a read, put the process
  655. to sleep.  On a write, wake up all those processes which have gone to
  656. sleep in this driver.  This will allow the processes to complete the read.
  657.  
  658. There are two new variables here, wakeups and wait_queue.  The wait_queue is
  659. a circular queue of processes which are sleeping.  It is FIFO, so that the
  660. process woken up is the first process which went to sleep.
  661.  
  662. The kernel handles the queue for us; all we need to do is supply a pointer
  663. to the queue and initialize it to NULL (i.e., the queue is empty).
  664.  
  665. We'll use the wakeups variable to tell us how many processes are taken off the
  666. wait_queue (i.e., woken up) -- which is the number of processes which have
  667. already gone to sleep.  So each time a process is slept on, we increment
  668. wakeups.  When a write request comes in, we wake up wakeups processes and reset
  669. wakeups to zero.
  670.  
  671. Simple, yes?  Now we get into the sticky part.
  672.  
  673. In the Guide, you see that you can choose two ways of sleeping -- interruptible
  674. or not.  Interruptible sleeps can be interrupted (i.e., the process is woken
  675. up) by signals (such as SIGUSR) and hardware interrupts.  Non-interruptible 
  676. sleeps can only be interrupted by hardware interrupts.  Not even a kill -9
  677. will wake up a non-interruptible process which is sleeping! Suppose you have a 
  678. signal handler in your process which will react to signal 30 (SIGUSR).  
  679. That is, you can do kill -30 <pid>.  What happens?
  680.  
  681. When the scheduler gets around to checking the signalled process for
  682. runnability, it sees that there is a signal pending.  This allows the process
  683. to continue to run where it left off, with a twist:  when the process leaves
  684. kernel mode (the driver call) and enters user mode, the signal handler is
  685. called (if there is one).  Once the signal handler function exits, one of
  686. two things can happen:
  687.  
  688. (1) If the original system call exited with -ERESTARTNOINTR,
  689.     then the process will continue as if it calls the system call again
  690.     with the same arguments.
  691. (2) If the original system call did not exit with -ERESTARTNOINTR,
  692.     but with -ERESTARTNOHAND or -ERESTARTSYS, then the process will 
  693.     continue exitting from the system call with -1, errno -EINTR.
  694. (3) If the original system call did not exit with -ERSTARTNOINTR,
  695.     -ERESTARTNOHAND, or -ERESTARTSYS, then the process will continue,
  696.     exitting from the system call with whatever was returned.
  697.  
  698. You can see most of this (if you can read mutilated 80386 assembly) in 
  699. <src>/kernel/sys_call.S and <src>/kernel/signal.c.  Although signal handling
  700. has been considerably revamped for 0.99pl8, the basic sequence of operations
  701. is intact across patch levels.  -ERESTARTNOHAND is new in 0.99pl8.
  702.  
  703. This is important -- the driver call should not be completed except for
  704. cleanup, since the kernel will return an error for you or redo the system
  705. call.  
  706.  
  707. When the process continues to run before calling the signal handler, it picks 
  708. up where it left off -- in the interruptible_sleep_on function.  This function 
  709. takes the process off the wait_queue automatically (which is nice).  But then 
  710. wakeups is not updated  (which is not so nice).  In that case, when a 
  711. subsequent write comes in, the number of sleeping processes reported will
  712. be wrong!
  713.  
  714. [pulpit-pounding mode on]
  715.  
  716. Although for this driver ignoring this is not such a big deal, it is sloppy
  717. programming for a driver.  Driver code must be so perfect that it operates
  718. like a well-oiled machine, with no slip-ups.  One error -- one bit of code
  719. that gets out of sync -- and you can at least annoy users and make them throw
  720. up their hands in frustration, and at worst panic the kernel and make users
  721. throw your code away in frustration!  Also, there is nothing worse than 
  722. spending time debugging an application when the bug is in the driver, or
  723. trying to code around a known driver flaw.
  724.  
  725. [pulpit-pounding mode off]
  726.  
  727. So how do we solve this out-of-sync problem?
  728.  
  729. Fact:  ignoring interrupts, all processes are atomic when they are in the 
  730. kernel.  That is, unless a process performs an operation which can sleep (like 
  731. the call to kmalloc we visited above), or a hardware interrupt comes in, the 
  732. flow of execution goes from entering the kernel to leaving the kernel, with no 
  733. time taken out to run anything else.  This does not mean that the code in user
  734. space gets to continue to run.  If the process leaves the system call and
  735. is not eligible to run, other processes may run and then later on the system
  736. call appears to have returned to the process.  More on that later.
  737.  
  738. That fact is good to know.  It means that as long as we are sure upon entering
  739. the test_write call that wakeups contains the correct number of sleeping
  740. processes, test_write will work 100%.  That is, unless a hardware interrupt
  741. comes in which causes the driver to execute an interrupt handler, we are safe,
  742. but here we have no such handler, and so we can ignore that for now.  We will 
  743. deal with interrupts in a later chapter.
  744.  
  745. So we know that write doesn't really have to be changed.  It's really the
  746. read that we're concerned about.  What we need to do is after we get out
  747. of interruptible_sleep_on() we see if we were genuinely woken up through
  748. a wakeup call, or if we were signalled.  If we were signalled, then
  749. we know that the write call wasn't the cause of the wakeup, and so we should
  750. really decrement wakeups.
  751.  
  752. Now for some loose ends.  Remember that upon signalling, the kernel only
  753. flags the signal for the process, and sets the process to a runnable state.
  754. That does not mean that it can run immediately.  Another process may get
  755. to run first, and that process may very well run the driver's write code,
  756. waking up all processes.  Of course, we can consider the signalled process
  757. to be still asleep when it gets the signal, because it has not yet run its
  758. signal handler.  So when that other process gets to run the write code, the
  759. number of sleeping processes is indeed correct, and wakeups is set to 0.
  760.  
  761. But now, when the signalled process is run again, the read code will attempt
  762. to decrement wakeups, making it -1!  The next write will display the wrong
  763. number of sleeping processes!
  764.  
  765. One thing saves us -- the fact that we can detect in the read code that the
  766. write code was executed, simply because wakeups is 0.  Remember that wakeups
  767. is incremented before the sleep, so it is guaranteed to be greater than 0 if
  768. the write code was not executed before waking up because of a signal.
  769.  
  770. So if the write code was executed, it really does not make sense to decrement
  771. wakeups, so we just say that only if wakeups is non-zero do we decrement.
  772.  
  773. To implement all this, add this code after the sleep:
  774.  
  775. ========================================
  776.   File Listing 7 (partial): testdata.c
  777. ========================================
  778.  
  779. if (current->signal & ~current->blocked) /* signalled? */
  780. {
  781.   printk("Process signalled.\n");
  782.   if (wakeups) wakeups--;
  783.   return -ERESTARTNOINTR; /* Will restart call automagically */
  784. }
  785.  
  786. ========================================
  787.  
  788.  
  789.  
  790. Now that you've got that straightened out, let's add some more confusion to
  791. the mix.  Suppose you're in the driver call, doing nice things, and then
  792. all of a sudden a nasty timer interrupt (task switch possibility) comes in.  
  793. What now?  Will there be a task switch?  No.  A RUNNING task in the kernel 
  794. cannot be  switched out, otherwise all hell would break loose.  Whew!  
  795. I'm glad we don't  have to pay attention to that!
  796.  
  797. Well, now that we've gone through all the possible ways signals can make
  798. your insides twist, you can code the driver.  Remember to put listing 7 into
  799. listing 6!
  800.  
  801. Here's how we're going to test this driver.  Several processes will call
  802. read (and sleep).  When they wake up, they're going to say that they were
  803. woken up (as opposed to printing out what they just read -- we already know
  804. that works).  One process will do a write to wake the other processes up.
  805. This is the trigger process.  Here is the code for the two types of processes:
  806.  
  807. ========================================
  808.       File Listing 8: data.c
  809. ========================================
  810.  
  811. #include <stdio.h>
  812. #include <sys/types.h>
  813. #include <unistd.h>
  814. #include <fcntl.h>
  815. #include <errno.h>
  816. #include <signal.h>
  817.  
  818. /* The reader process */
  819.  
  820. void signal_handler(int x)
  821. {
  822.   printf("Called signal handler\n");
  823.   signal(SIGUSR1, signal_handler); /* Reset signal handler */
  824. }
  825.  
  826. void main(void)
  827. {
  828.   int fd;
  829.   char buff[128];
  830.   int rtn;
  831.   
  832.   signal(SIGUSR1, signal_handler); /* Setup signal handler */
  833.  
  834.   fd = open("/dev/testdata",O_RDWR);
  835.   printf("/dev/testdata opened, fd=%d\n",fd);
  836.   if (fd<=0) exit(0);
  837.  
  838.   rtn = read(fd,buff,sizeof(buff));
  839.   printf("Read returns %d\n",rtn);
  840.   if (rtn<0)
  841.   {
  842.     perror("read");
  843.     exit(1);
  844.   }
  845.   printf("Process woken up!\n");
  846.   close(fd);
  847. }
  848.  
  849. ========================================
  850.  
  851. ========================================
  852.       File Listing 9: trigger.c
  853. ========================================
  854.  
  855. #include <stdio.h>
  856. #include <sys/types.h>
  857. #include <unistd.h>
  858. #include <fcntl.h>
  859. #include <errno.h>
  860. #include <signal.h>
  861.  
  862. /* The writer process */
  863.  
  864. void main(int argc, char **argv)
  865. {
  866.   int fd;
  867.   char buff[128];
  868.   int rtn;
  869.   
  870.   fd = open("/dev/testdata",O_RDWR);
  871.   printf("/dev/testdata opened, fd=%d\n",fd);
  872.   if (fd<=0) exit(0);
  873.  
  874.   if (argc>1)
  875.   {
  876.     kill(atoi(argv[1]),SIGUSR1);
  877.     exit(0);
  878.   }
  879.   rtn = write(fd,buff,sizeof(buff));
  880.   if (rtn<0)
  881.   {
  882.     perror("write");
  883.     exit(1);
  884.   }
  885.   close(fd);
  886. }
  887.  
  888. ========================================
  889.  
  890. Compile these programs using gcc.  Now run two or three of the data processes:
  891.  
  892.   data &
  893.  
  894. The last thing each of these processes should print is
  895.  
  896.   Process going to sleep.
  897.  
  898. because all of these processes are asleep.  Now run the trigger program:
  899.  
  900.   trigger
  901.  
  902. This should wake up all the other processes, which should say,
  903.  
  904.   Process woken up!
  905.  
  906. Had the read function returned an error (like EINTR), they would have said
  907.  
  908.   read: <error text>
  909.  
  910. Now, let's test to see if the signal detection and restart mechanism works.
  911. Run a single data process in the background via "data &".  Remember it's
  912. pid.  Now, run the trigger process with that pid as an argument:
  913.  
  914.   trigger <pid>
  915.  
  916. This will signal <pid> instead of waking it up via write.  The driver should
  917. say, 
  918.  
  919.   Process signalled.
  920.   Called signal handler
  921.  
  922. but the process should not wake up, since we restarted the call.  Only a
  923. write will stop the call.
  924.  
  925. ++++++++++++++++++++++
  926.     EXPERIMENT 3
  927. ++++++++++++++++++++++
  928.  
  929. Re-write the driver so that instead of always restarting the call, it returns
  930. with EINTR on signal when the read call's count is a special value or values
  931. (say anything less than 1000).  Test to see if the read call returns EINTR when
  932. the trigger program signals the reading process.
  933.  
  934. ++++++++++++++++++++++
  935.  
  936. ------------------------------------------------------------------------
  937.  
  938. CHAPTER SIX: I want this, that, that...no, THIS, and that.  Or, selects!
  939. -----------
  940.  
  941. The select call is one of the most useful calls created for interfacing to
  942. drivers.  Without it, or a function like it, if you wanted to check a 
  943. driver for readiness, you would have to poll it regularly.  Worse, you
  944. would not be able to check multiple drivers for readiness at the same time!
  945.  
  946. But enough of this.  You have select, so rejoice and be happy.
  947.  
  948. As already implied by the first paragraph, the select system call allows
  949. a process to check multiple drivers for readiness.  For example, suppose 
  950. you wanted the process to sit around and wait for one of two file
  951. descriptors to be ready for reading.  Usually, if a descriptor is not ready
  952. for reading and you read it, it will put your process to sleep (or "block"). 
  953. But you can only read one file descriptor at a time, and here you want to
  954. essentially block on _two_ fd's.
  955.  
  956. In that case, you use the select call.  The syntax of select was already
  957. explained in the Guide, so let's go about implementing a select function in
  958. our driver.
  959.  
  960. Add the following code to the driver, and put the test_select function in
  961. the fops structure:
  962.  
  963. ========================================
  964.   File Listing 10 (partial): testdata.c
  965. ========================================
  966.  
  967. static int test_select(struct inode *inode, struct file *file,
  968.                        int sel_type, select_table *wait)
  969. {
  970.   printk("Driver entering select.\n");
  971.   if (sel_type==SEL_IN) /* ready for read? */
  972.   {
  973.     if (wakeups) /* Any process is sleeping in here */
  974.     {
  975.       select_wait(&wait_queue, wait);
  976.       printk("Driver not ready\n");
  977.       return 0;  /* Not ready yet */
  978.     }
  979.     return 1;  /* Ready */
  980.   }
  981.   return 1;  /* Always ready for writes and exceptions */
  982. }
  983.  
  984. ========================================
  985.  
  986. Here's what this function does.  When a process issues a select call with
  987. this driver as one of the fd's to select on, the kernel will call
  988. test_select with sel_type being SEL_IN.  If wakeups is non-zero (that is,
  989. processes have read without a process writing) then we will say that the
  990. driver is not ready for reading.  In this case, select_wait will add the
  991. process to the wait_queue and immediately return.  The return of 0 indicates
  992. that the driver is not ready for the operation.
  993.  
  994. For any other type of operation (or if there are no processes sleeping in
  995. read) we say the driver is ready (return 1).
  996.  
  997. The only thing that must be remembered is that we are using the same
  998. wait_queue structure for processes sleeping in read and processes sleeping
  999. in select.  This means that writing to the driver will wake up both types of
  1000. processes.  If desired, a different wait_queue could be used, and the
  1001. appropriate wake up code would have to be written.
  1002.  
  1003. Compile this new code into the kernel.  We will test this driver by writing
  1004. a new type of process which will call the select system call.  Here is the
  1005. new process' code:
  1006.  
  1007. ========================================
  1008.         File Listing 11: sel.c
  1009. ========================================
  1010.  
  1011. #include <stdio.h> /* Doesn't hurt, can only help! */
  1012. #include <fcntl.h>
  1013. #include <sys/time.h> /* For FD_* and select */
  1014.  
  1015. void main(void)
  1016. {
  1017.   int fd;
  1018.   int rtn;
  1019.   fd_set read_fds;
  1020.  
  1021.   fd = open("/dev/testdata", O_RDWR);
  1022.   printf("/dev/testdata opened, fd=%d\n",fd);
  1023.   if (fd<=0) exit(0);
  1024.   printf("Entering select...\n");
  1025.   FD_ZERO(&read_fds);
  1026.   FD_SET(fd,&read_fds);
  1027.   rtn = select(&read_fds, NULL, NULL, NULL);
  1028.   if (rtn<0)
  1029.   {
  1030.     perror("select");
  1031.     exit(0);
  1032.   }
  1033.   printf("Select returns %d\n",rtn);
  1034. }
  1035.  
  1036. ========================================
  1037.  
  1038. When the kernel is re-loaded, the first test we will perform is to see
  1039. whether the select call returns immediately given that no processes are
  1040. sleeping in read.  Just run sel -- no need to run it in the background.
  1041. You should see something like:
  1042.  
  1043. Entering select...
  1044. Driver entering select.
  1045. Select returns 1
  1046.  
  1047. This is as it should be -- select has determined that one file descriptor is
  1048. ready for reading.
  1049.  
  1050. Our next test is to see whether select sleeps properly.  Run this:
  1051.  
  1052. data &
  1053. sel &
  1054. trip
  1055.  
  1056. When sel is run, you should see:
  1057.  
  1058. Entering select...
  1059. Driver entering select.
  1060. Read not ready
  1061. Driver entering select.
  1062. Read not ready
  1063.  
  1064. The select call in the kernel calls the test_select function again once if
  1065. the first time the driver is not ready.  However, the process is only added
  1066. to the wait queue once -- the first time.
  1067.  
  1068. Once the trip program is run, you should see:
  1069.  
  1070. Process has woken up!
  1071. Read returns 1024
  1072. Driver entering select.
  1073. Select returns 1
  1074.  
  1075. That is, the data process woke up due to the write, as did the sel process. 
  1076. Note that the test_select function is called once again when the sel process
  1077. is woken up.  This is also a consequence of the kernel design, and is
  1078. nothing to worry about.  Those who are interested in the inner workings of
  1079. the select call should look in the file <src>/fs/select.c.
  1080.  
  1081. A word about signals and select.  Since the select call in the driver does
  1082. not return any error code -- just 0 or non-0 -- there is no way to decide
  1083. whether the select call should be restarted or not.  Select will return -1,
  1084. errno EINTR if interrupted by a signal.
  1085.  
  1086. ------------------------------------------------------------------------
  1087.  
  1088. CHAPTER SEVEN: This next chap -- oh, hello! -- this next chapter is about
  1089. -------------  interrupts.
  1090.  
  1091. This chapter will be one of the most difficult chapters to go through as a
  1092. tutorial, since some means of generating interrupts must be used to test
  1093. things with.  Furthermore, the interrupt must be one which is currently
  1094. unused by the system, and one must be willing to mess around with a hardware
  1095. device which is connected to the IRQ.
  1096.  
  1097. I will start out with something more controlled than external interrupts --
  1098. internal, or software, interrupts.
  1099.  
  1100. Why internal interrupts?  There really is not such a big difference between
  1101. internal and external interrupts.  Certainly an IRQ is generated by a
  1102. hardware device, but the hardware IRQ results in a software interrupt.  I
  1103. will discuss the required changes for dealing with hardware rather than
  1104. software interrupts later in this chapter.
  1105.  
  1106. Note:  The following paragraphs deal with 80386/80486 specific stuff.  Those
  1107. who are not really interested in the "why" of Linux interrupts may skip
  1108. ahead!
  1109.  
  1110. To be able to use interrupts, we must first understand how Linux handles
  1111. interrupts.  Interrupts most often require a transfer of execution control
  1112. from one code segment to another, and this may be accomplished in two ways. 
  1113. The first is by specifying the descriptor of the other executable segment,
  1114. and the second is by a "gate".
  1115.  
  1116. In Linux, three functions are used to initialize gates:  set_intr_gate,
  1117. set_trap_gate, and set_system_gate.
  1118.  
  1119. set_intr_gate sets up a 32-bit interrupt gate with descriptor privilege
  1120. level (DPL) 0 (the most privileged level).
  1121.  
  1122. set_trap_gate sets up a 32-bit task gate with DPL 0.
  1123.  
  1124. set_system_gate sets up a 32-bit task gate with DPL 3.
  1125.  
  1126. Each of these setups enter the gate into the interrupt descriptor table
  1127. (IDT) so that when an INT n instruction is performed, the gate in the IDT
  1128. corresponding to n is executed.
  1129.  
  1130. THIS ENDS 80386/80486 DISCUSSION.
  1131.  
  1132. The three Linux calls allow us to install an interrupt handler for any
  1133. interrupt from 0x00 to 0xFF.  We will use set_intr_gate to install an
  1134. interrupt handler into interrupt 0x90.
  1135.  
  1136.